<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>spa项目的server层分析与使用factory创建服务</title>
		<script src="../org/angular.min.js"></script>
		<script src="../org/jquery.min.js"></script>
	</head>

	<body>
		<div ng-app="hd">
			<div ng-controller="ctrl1">
				<table width="600" border="1px">
					<tr>
						<td>名称</td>
						<td>链接</td>
					</tr>
					<tr ng-repeat='v in data.webs'>
						<td>{{v.name}}</td>
						<td>{{v.url}}</td>
					</tr>
				</table>
			</div>
			<hr />
			<div ng-controller="ctrl2">
				<table width="600" border="1px">
					<tr>
						<td>名称</td>
						<td>链接</td>
					</tr>
					<tr ng-repeat='v in data.webs'>
						<td>{{v.name}}</td>
						<td>{{v.url}}</td>
					</tr>
				</table>
				<h1>{{webs.name}}</h1>
				<button ng-click = "deleteAll()">删除所有</button>
			</div>
			
		</div>
		<script>
			var m = angular.module('hd', []);
			m.factory('serverHttp', ['$http', function($http) {
				var obj = {
					data: {webs:[]},
					all: function() {
						return $http({   //注意此处一定要有return
							url: '$httpPhp.php'
						}).then(function(response) { 
							obj.data.webs = response.data;
							return obj.data;
						});
					},
					find: function(id) {
						return this.all().then(function(data){
							for(var i=0; i<data.length; i++){
							    if(data[i].id = id){
							    	return data[i];
							    }
						    }
						})
						
					},
					removeAll:function(){
						obj.data.webs = [];
					}
				}
				return obj;
			}]);
			m.controller('ctrl1', ['$scope', 'serverHttp', function($scope, serverHttp) {
				serverHttp.all().then(function(data) {
					$scope.data = data;
				});

			}]);
			m.controller('ctrl2', ['$scope', 'serverHttp', function($scope, serverHttp) {
				serverHttp.all().then(function(data) {
					$scope.data = data;
				});
                serverHttp.find(1).then(function(data){
                	$scope.webs = data;
                })
                $scope.deleteAll = function(){
                	serverHttp.removeAll();
                }
			}]);
		</script>
	</body>

</html>